// pages/search/search.js
import request from '../../untils/request'
let isSend = false //函数节流用关键字
Page({

  /**
   * 页面的初始数据
   */
  data: {
    placeholderContent: '', //placeholder内容
    hotList: [], //热搜榜数据
    searchContent: "", //用户输入的表单数据
    searchList: [], //关键字模糊匹配数据
    historyList:[],//搜索历史记录
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getInitData()
    //获取历史记录
    this.getSearchHistory()
  },
  //获取初始化数据
  async getInitData() {
    let placeholderData = await request('/search/default')
    let hotListData = await request('/search/hot/detail')
    this.setData({
      placeholderContent: placeholderData.data.showKeyword,
      hotList: hotListData.data
    })
  },
  //搜索表单发生改变回调
  handleInputChange(event) {
    console.log(event)
    this.setData({
      searchContent: event.detail.value.trim()
    })
    //函数防抖
    if (isSend) {
      return
    }
    isSend = true
    this.getSearchList()
    setTimeout(() => {
      isSend = false
    }, 300)

  },
  //获取搜索数据函数
  async getSearchList() {
    if(!this.data.searchContent){
      this.setData({
        searchList:[]
      })
      return
    }
    let {searchContent,historyList}=this.data
    //关键字发请求
    let searchListData = await request('/search', {
      keywords: this.data.searchContent,
      limit: 10
    })
    this.setData({
      searchList: searchListData.result.songs
    })

    //将搜索的关键子添加到搜索历史记录中
    if(historyList.indexOf(searchContent) !==-1){
    
      historyList.splice(historyList.indexOf(searchContent),1)
    }
    historyList.unshift(searchContent)
 
   this.setData({
     historyList
   })
   wx.setStorageSync('searchHistory', historyList)
  },

  //获取本地历史记录
  getSearchHistory(){
    let historyList=wx.getStorageSync('searchHistory')
    if( historyList){
      this.setData({
        historyList
      })
    }
  },
  //清空搜索内容
  clearSearchContent(){
    console.log('111')
    this.setData({
      searchContent:"",
      searchList:[]
    })
  },

  //删除历史记录
  deleteSearchHistory(){
    //清空data中的historyList
    wx.showModal({
      content:'确认删除吗',
      success:(e)=>{
let confirm=e.confirm
if(confirm){
  this.setData({
    historyList:[]
  })
  //移除本地历史搜索记录
wx.removeStorageSync('searchHistory')
}else{

}
      }
      
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})